import os, time, logging, asyncio
import re, requests, json

async def get_ipaddress(proxy_url):
    # return await xiecaiyun_get_ip()
    return await qiyun_get_ip(proxy_url)


## ---协采云-------------------------------------
async def xiecaiyun_get_ip():
    # time.sleep(3)
    url = 'http://19986287991.user.xiecaiyun.com/api/proxies?action=getJSON&key=NP89DF81F2&count=20&word=&rand=true&norepeat=false&detail=false&ltime=&idshow=false'
    response = requests.get(url)
    arr = json.loads(response.text)

    if arr['success']:
        ip = f"{arr['result'][0]['ip']}:{arr['result'][0]['port']}"
        print(f"IP Company:协采云")
        return ip
    else:
        return None


## ---奇云-------------------------------------
ipArray = []

async def qiyun_get_ip(proxy_url):  # 定义 process_array 函数，用于处理获取到的数组，将其添加到全局变量 BB 中，然后将其从 BB 中移除
    global ipArray
    i = 0
    while i < 20:
        i = i + 1
        if len(ipArray) < 10:
            await asyncio.sleep(3)
            await _get_ipjson_array(proxy_url)
        if len(ipArray) > 1:
            print(f"IP Company:奇云")
            return ipArray.pop()


async def _get_ipjson_array(proxy_url):
    global ipArray
    # url = 'http://gev.qydailiip.com/api/?apikey=977e3d0aa43582bc0ecabccecdd1c26d0b34fe3d&num=3&type=json&line=win&proxy_type=secret&end_time=0'

    # url="http://sea.qydailiip.com/api/?apikey=b466ca6bd1d2a7d01fb5b4c61448763ad8f0b0fa&num=50&type=json&line=win&proxy_type=secret"
    # b466ca6bd1d2a7d01fb5b4c61448763ad8f0b0fa 客服2023.11.8 21：33

    response = requests.get(proxy_url)
    pattern = r'ERROR'
    ret = bool(re.search(pattern, response.text))
    if not ret:
        if is_json(response.text):
            arr = json.loads(response.text)
            for item in arr:
                ipArray.append(item)
        else:
            lines = [line for line in response.text.splitlines() if line]
            # 如果只需要第一行，可以直接使用
            for item in lines:
                ipArray.append(item)

def is_json(myjson):
    try:
        json_object = json.loads(myjson)
    except ValueError as e:
        return False
    return True


# ip =  xiecaiyun_get_ip()



